
package com.platform.modules.event;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.EasyPoiUtils;
import com.platform.common.utils.RestResponse;
import com.platform.modules.event.entity.EventCalendarCategoryEntity;
import com.platform.modules.event.entity.EventCalendarEntity;
import com.platform.modules.event.service.EventCalendarBranchService;
import com.platform.modules.event.service.EventCalendarCategoryService;
import com.platform.modules.event.service.EventCalendarService;
import com.platform.modules.event.service.EventCategoryService;
import com.platform.modules.oss.cloud.UploadFactory;
import com.platform.modules.oss.entity.SysOssEntity;
import com.platform.modules.oss.service.SysOssService;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.sys.entity.SysConfigEntity;
import com.platform.modules.sys.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 模块表Controller
 *
 * @author
 * @date 2020-10-16 09:39:57
 */
@RestController
@RequestMapping("event/calendar")
public class EventCalendarController extends AbstractController {
    @Autowired
    private EventCalendarService eventCalendarService;
    @Autowired
    private EventCategoryService eventCategoryService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private EventCalendarCategoryService eventCalendarCategoryService;
    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private EventCalendarBranchService eventCalendarBranchService;
    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("event:calendar:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<EventCalendarEntity> list = eventCalendarService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询模块表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("event:calendar:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = eventCalendarService.queryPage(params);
        SysConfigEntity config = sysConfigService.getOne(new QueryWrapper<SysConfigEntity>().eq("PARAM_KEY","EVENT_CALENDAR_LINK"));

        return RestResponse.success().put("page", page).put("link",config.getParamValue());
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("event:calendar:info")
    public RestResponse info(@PathVariable("id") String id) {
        EventCalendarEntity eventCalendar = eventCalendarService.getById(id);

        //获取活动所属的卡种列表
        List<String> categoryIdList = eventCategoryService.queryCategoryList(id);
        eventCalendar.setCategoryIds(categoryIdList);

        //获取活动所属的支行列表
        List<String> BranchIdList = eventCalendarBranchService.queryBranchIdList(id);
        eventCalendar.setBranchIds(BranchIdList);

        return RestResponse.success().put("eventCalendar", eventCalendar);
    }

    /**
     * 新增活动日历表
     *
     * @param eventCalendar
     * @return RestResponse
     */
    @SysLog("新增活动日历表")
    @RequestMapping("/save")
    @RequiresPermissions("event:calendar:save")
    public RestResponse save(@RequestBody EventCalendarEntity eventCalendar) {

        eventCalendar.setCreateTime(new Date());
        if (eventCalendar.getEndTime() == null || eventCalendar.getEndTime().equals("")) {
            eventCalendar.setEndTime(null);
        }
        if (eventCalendar.getStartTime() == null || eventCalendar.getStartTime().equals("")) {
            eventCalendar.setStartTime(null);
        }
        eventCalendarService.add(eventCalendar);


        return RestResponse.success();
    }

    /**
     * 修改表
     *
     * @param eventCalendar
     * @return RestResponse
     */
    @SysLog("修改活动日历表")
    @RequestMapping("/update")
    @RequiresPermissions("event:calendar:update")
    public RestResponse update(@RequestBody EventCalendarEntity eventCalendar) {
        if(eventCalendar.getEndTime()==null||eventCalendar.getEndTime().equals("")){
            eventCalendar.setEndTime(null);
        }
        if(eventCalendar.getStartTime()==null||eventCalendar.getStartTime().equals("")){
            eventCalendar.setStartTime(null);
        }
        eventCalendar.setUpdateTime(new Date());
//        if(StringUtils.isBlank(eventCalendar.getWeeks())){
//            eventCalendar.setWeeks("-99");
//        }
        eventCalendarService.update(eventCalendar);

        return RestResponse.success();
    }

    /**
     * 根据主键删除模块表
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除活动日历表")
    @RequestMapping("/delete")
    @RequiresPermissions("event:calendar:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        eventCalendarService.deleteBatch(ids);

        return RestResponse.success();
    }

    @SysLog("修改活动日历跳转")
    @RequestMapping("/updateLink")
    @RequiresPermissions("event:calendar:update")
    public RestResponse update(@RequestParam Map<String, Object> params) {

        SysConfigEntity config = sysConfigService.getOne(new QueryWrapper<SysConfigEntity>().eq("PARAM_KEY","EVENT_CALENDAR_LINK"));
        config.setParamValue(params.get("value").toString());
        sysConfigService.update(config);
        return RestResponse.success();
    }

    /**
     * 上传文件
     * @param file file
     * @return RestResponse
     */
    @SysLog("活动日历批量导入")
    @RequestMapping("/upload")
    @RequiresPermissions("event:calendar:save")
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        if (null == file || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }


        InputStream in = file.getInputStream();
        XSSFWorkbook xssfWorkbook=new XSSFWorkbook(in);
        Map<String, XSSFPictureData> map=getPictures(xssfWorkbook.getSheetAt(0));



        List<EventCalendarCategoryEntity> categoryList =eventCalendarCategoryService.list(new QueryWrapper<EventCalendarCategoryEntity>().eq("status",1));

        Map<String,String> categoryMap = new HashMap<>();

        for (EventCalendarCategoryEntity e:categoryList
        ) {
            categoryMap.put(e.getTitle().substring(0,2),e.getId());

        }
        //上传文件
        AtomicInteger atomicInteger = new AtomicInteger(0);
        List<EventCalendarEntity> eventEntityList = EasyPoiUtils.importExcelToMap(file, (row) -> {
            atomicInteger.incrementAndGet();
            if (StringUtils.isNotBlank(row[0])) {
                //为空判断
                if (StringUtils.isBlank(row[0]) || StringUtils.isBlank(row[2]) ) {
                    throw new BusinessException("关键数据为空！");
                }
                EventCalendarEntity eventEntity = new EventCalendarEntity();
                eventEntity.setCategoryId(categoryMap.get(row[0].trim().substring(0,2)));
                if(StringUtils.isNotEmpty(row[1].trim())){
                    eventEntity.setSort(Integer.valueOf(row[1].trim()));
                }
                eventEntity.setTitle(row[2].trim());
                eventEntity.setLink(row[3].trim());
                eventEntity.setCover(row[4].trim()==null?"":"");
                eventEntity.setIntroduce(row[5].trim());
                eventEntity.setContent(row[6]);
                String startTimeStr = row[7].trim();
                String endTimeStr = row[8].trim();
                int compareTo = DateUtils.stringToDate(endTimeStr, DateUtils.DATE_PATTERN).compareTo(DateUtils.stringToDate(startTimeStr, DateUtils.DATE_PATTERN));
                if(compareTo<0){
                    throw new BusinessException("开始时间大于结束时间请检查数据！");
                }
                eventEntity.setStartTime(row[7].trim());
                eventEntity.setEndTime(row[8].trim());
                eventEntity.setRow(atomicInteger.get());
                List<String> list =new ArrayList<String>();
                String trim = row[0].trim();
                if(trim.contains(",")){
                    String[] split = trim.split(",");
                    for (int i= 0 ;i<split.length ;i++){
                        list.add( categoryMap.get(split[i].substring(0,2)));
                    }
                }else {
                    list.add(eventEntity.getCategoryId());
                }
                eventEntity.setCategoryIds(list);
                return eventEntity;
            }
            return null;

        });
        if (eventEntityList.size() <= 0) {
            return RestResponse.error("无可录入数据！");
        }

//        List<EventCalendarEntity>  abnormalList = new ArrayList<>();
        List<EventCalendarEntity>   normalList = new ArrayList<>();
        for (EventCalendarEntity e:eventEntityList
        ) {
//            String startTime = e.getStartTime();
//            long time = DateUtils.stringToDate(startTime, DateUtils.DATE_PATTERN).getTime();
//            e.setStartTime(String.valueOf(time));
            normalList.add(e);

//            if (StringUtils.isNumeric(e.getStartTime())){
//                normalList.add(e);
//            }else {
//                abnormalList.add(e);
//            }
        }
        Map<String, String> url = uploadPic(map);
        eventCalendarService.addBatch(normalList,url);



        return RestResponse.success();
    }

    private static Map<String, XSSFPictureData> getPictures(XSSFSheet xssfSheet){

        Map<String,XSSFPictureData> map=new HashMap<>();
        List<XSSFShape> list;
        try {
            list=xssfSheet.getDrawingPatriarch().getShapes();
        }catch (NullPointerException e){
            return map;
        }

        if(null != list || list.size()>0) {
            for (XSSFShape shape : list) {
                XSSFPicture picture = (XSSFPicture) shape;
                XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) picture.getAnchor();
                XSSFPictureData pdata = picture.getPictureData();
                String key = xssfClientAnchor.getRow1() + "";
                if (xssfClientAnchor.getCol1() == 4) {
                    map.put(key, pdata);
                }
            }
        }
        return map;
    }

    private  Map<String, String> uploadPic(Map<String, XSSFPictureData> pic){
        Map<String,String> map = new HashMap<>();

        for(String  key : pic.keySet()){

            XSSFPictureData data =  pic.get(key);

            //上传文件
            String suffix = key;
            String url = UploadFactory.build().uploadSuffix(data.getData(), suffix);

            //保存文件信息
            SysOssEntity ossEntity = new SysOssEntity();
            ossEntity.setUrl(url);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);
            map.put(key,url);
        }
        return map;
    }
}
